package be.js.sqlCodeGenerator;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbutils.DbUtils;

/**
 * 
 * Helper class for database related work.
 * - opens a db connection on instanciation
 * - a method returning a resultset containing all tables in the schema
 * - a method returning a resultset containing all columns in a given table
 *   in the schema.
 * 
 * $Id: DatabaseHelper.java 81 2013-03-12 21:15:39Z johan.schamp@gmail.com $ 
 * @author johan schamp (johan.schamp@gmail.com)
 * 
 */

public class DatabaseHelper {
	
	private Connection connection;	
	private DatabaseMetaData databaseMetaData = null;
	private String schema = null;
	
	/**
	 * 
	 * @param jdbcDriver the JDBC driver class
	 * @param jdbcConnectionUrl the connection url to the database instance
	 * @param jdbcUser the user name
	 * @param jdbcPassword the password
	 * @param schema the schema name
	 */
	public DatabaseHelper(String jdbcDriver, String jdbcConnectionUrl, String jdbcUser, String jdbcPassword, String schema) {
		try {
			
			Class.forName(jdbcDriver);
			this.connection = DriverManager.getConnection(jdbcConnectionUrl, jdbcUser, jdbcPassword);
			this.databaseMetaData = connection.getMetaData();
		
			this.schema = schema;
			
			
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("Cannot load JDBC driver.", e);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} 
	}
	
	/**
	 * Returns a resultset containing all tables in the schema
	 * 
	 * @return the resultset with table names
	 * @throws SQLException
	 */
	public ResultSet getTables() throws SQLException {
		return databaseMetaData.getTables(null, this.schema, null, new String[] { "TABLE" });
	}
	
	/**
	 * Returns a resultset containing all columns for a given table
	 * in the schema.
	 * 
	 * @param tableName the table name to return columns from
	 * @return the resultset with column names
	 * @throws SQLException
	 */
	public ResultSet getColumns(String tableName) throws SQLException {
		return databaseMetaData.getColumns(null, this.schema, tableName, null);
	}
	
	/**
	 * Closes the connection ignoring all exceptions.
	 */
	public void closeQuitely(){
		DbUtils.closeQuietly(connection);
	}
}
